package cn.leedsoft.and.crimeintent.controller.run_tracker;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.*;
import android.widget.ListView;
import android.widget.TextView;
import cn.leedsoft.and.crimeintent.R;
import cn.leedsoft.and.crimeintent.manager.run_tracker.RunDatabaseHelper;
import cn.leedsoft.and.crimeintent.manager.run_tracker.RunManager;
import cn.leedsoft.and.crimeintent.common.SQLiteCursorLoader;
import cn.leedsoft.and.crimeintent.model.run_tracker.Run;

import java.text.SimpleDateFormat;

/**
 * Created by leeds on 2016/9/6 14:20.
 */
public class RunListFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor>{//listFragment 只有一个数据源。所以只需要一个loader。直接实现接口即可。
    private static final String TAG = "RunListFragment";
    private static final int REQ_VIEW_RUN = 1;
    private static final int REQ_NEW_RUN = 0;

    public static RunListFragment newInstance() {

        Bundle args = new Bundle();

        RunListFragment fragment = new RunListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.run_tracker, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.run_menu_new_run:
                Intent intent = new Intent(getActivity(), RunActivity.class);
                startActivityForResult(intent, REQ_NEW_RUN);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        Intent intent = new Intent(getActivity(), RunActivity.class);
        intent.putExtra(RunFragment.ARG_RUN_ID, id);
        startActivityForResult(intent, REQ_VIEW_RUN);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQ_NEW_RUN:
            case REQ_VIEW_RUN:
//                mRunCursor.requery();
//                ((RunCursorAdapter) getListAdapter()).notifyDataSetChanged();
                getLoaderManager().restartLoader(0, null, this);//刷新 loader
                Log.d(TAG, ">>>>旅程列表已刷新");
                break;

        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        setHasOptionsMenu(true);

        getLoaderManager().initLoader(0, null, this);//通知LoadManager开始工作
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        System.out.println(">>>>>>>>>>>>>>>tttttttt");
        return super.onCreateView(inflater, container, savedInstanceState);
    }
//loaderCallback 接口---begin
    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        return new RunListCursorLoader(getActivity());
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {//数据在后台一完成加载， onLoadFinished(Loader<Cursor>, Cursor)方法就会在主线程上被调用
        RunCursorAdapter adapter = new RunCursorAdapter(getActivity(), (RunDatabaseHelper.RunCursor)data);
        setListAdapter(adapter);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {//在没有可加载数据时， onLoaderReset(Loader<Cursor>)方法会被调用。安全起见，我们设置列表adapter值为空，以停止使用cursor
        setListAdapter(null);//stop using the cursor via the adapter
    }
    //loaderCallback 接口---end
    private static class RunCursorAdapter extends CursorAdapter {
        private RunDatabaseHelper.RunCursor mCursor1;

        public RunCursorAdapter(Context context, RunDatabaseHelper.RunCursor runCursor) {
            super(context, runCursor, 0);
            mCursor1 = runCursor;
        }

        @Override//Makes a new view to hold the data pointed to by cursor.
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            return inflater.inflate(android.R.layout.simple_list_item_1, parent, false);//android.R.layout.simple_list_item_1 查看源代码，就一个textview
        }

        @Override//Bind an existing view to the data pointed to by cursor
        public void bindView(View view, Context context, Cursor cursor) {//context Interface to application's global information
            Run run = mCursor1.getRun();

            TextView textView = (TextView) view;
            textView.setText(context.getString(R.string.cell_text, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(run.getStartDate())));
        }
    }

    private static class RunListCursorLoader extends SQLiteCursorLoader {

        public RunListCursorLoader(Context context) {
            super(context);
        }

        @Override
        protected Cursor loadCursor() {
            return RunManager.getInstance(getContext()).queryRuns();
        }
    }
}
